Paul's JavaScript Examples | ||
This simple Javascript routine checks if a date entered conforms to the dd-mmm-yy (eg. 01-Jan-98 or 01-Jan) specification and will return an error message with a suggestion as to what may be wrong to the user.
Example
Please use the 01-jan-80 type format. (As using eg. 08-07 style may mean either 8th July or 7th August and has caused errors!) The year part of this field is optionalUsage
<input name="mydate" value="" size=9 maxlength=10 onChange="Check_Date(this.value)">
Source
<SCRIPT LANGUAGE="javascript"> <!-- function Check_Date(item) { var returnVal = false checkVal = 0 if (item.length < 6) { checkVal = 1 } if (item.length > 6) { if (item.substring(6,7) != '-') { checkVal = 2 } if (isNaN(parseInt(item.substring(item.length-2,item.length))) || parseInt(item.substring(item.length-2,item.length)) < 0) { checkVal = 5 } } if (item.substring(2,3) != '-') { checkVal = 2 } if (!isNaN(parseInt(item.substring(3,6)))) { checkVal = 3 } else { month = item.substring(3,6) month = month.toLowerCase() if ( month != 'jan' && month != 'feb' && month != 'mar' && month != 'apr' && month != 'may' && month != 'jun' && month != 'jul' && month != 'aug' && month != 'sep' && month != 'oct' && month != 'nov' && month != 'dec' ) { checkVal = 3 } } if (isNaN(parseInt(item.substring(0,2))) || parseInt(item.substring(0,2)) < 1 || parseInt(item.substring(0,2)) > 31) { checkVal = 4 } if (checkVal == 0) returnVal = true if (checkVal == 1) fout = 'Date apparently not filled in according\nto specifications.' if (checkVal == 2) fout = 'Day format to use is dd-mmm-yy. Where\ndd = day eg. \'01\', mmm = month eg. \'May\' and\nyy is year eg \'75\\nWith \'-\' separating these values!' if (checkVal == 3) fout = 'Incorrect entry of month, Valid entries are:\njan, feb, mar, apr, may, jun\njul, aug, sep, oct, nov, dec' if (checkVal == 4) fout = 'Incorrect entry of day, figure should be 01 - 31' if (checkVal == 5) fout = 'Incorrect entry of year, figure should be 00 - 99' if (returnVal == false) { alert('Your date entry appears incorrect!\n \nError Report:\n' + fout) } return returnVal } // --> </SCRIPT>